/**
 * 
 */
package com.zuipin.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zuipin.entity.BalanceRecord;
import com.zuipin.entity.DrawLevelGroup;
import com.zuipin.entity.IntegralRecord;
import com.zuipin.entity.LockDraw;
import com.zuipin.entity.Member;
import com.zuipin.entity.MemberLevel;
import com.zuipin.entity.Prize;
import com.zuipin.entity.SysUser;
import com.zuipin.entity.WinningRecord;
import com.zuipin.entity.WinningRule;
import com.zuipin.entity.shoppingCart.RuleSet;
import com.zuipin.entity.shoppingCart.RuleType;
import com.zuipin.entity.shoppingCart.Status;
import com.zuipin.enums.BalanceType;
import com.zuipin.enums.IntegralType;
import com.zuipin.enums.PrizeType;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.Result;
import com.zuipin.mapper.LockDrawMapper;
import com.zuipin.mapper.WinningRuleMapper;
import com.zuipin.service.IBalanceRecordService;
import com.zuipin.service.IDrawLevelGroupService;
import com.zuipin.service.IDrawNumService;
import com.zuipin.service.IIntegralRecordService;
import com.zuipin.service.IMemberLevelService;
import com.zuipin.service.IMemberRecordService;
import com.zuipin.service.IMemberService;
import com.zuipin.service.IPrizeService;
import com.zuipin.service.IRedPacketService;
import com.zuipin.service.IRuleSetService;
import com.zuipin.service.IShoppingCartService;
import com.zuipin.service.IWinningRecordService;
import com.zuipin.service.IWinningRuleService;
import com.zuipin.util.ArithUtil;
import com.zuipin.util.ConstantsUtil;
import com.zuipin.util.DateUtils;
import com.zuipin.util.RedisLock;
import com.zuipin.util.RedisUtils;
import com.zuipin.util.StringUtil;

/** 
 * @ClassName: WinningRuleServiceImpl 
 * @author wuyicheng
 * @time 2017年5月5日上午11:48:22 
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WinningRuleServiceImpl implements IWinningRuleService {
	
	@Resource
	private WinningRuleMapper		winningRuleMapper;
	
	@Resource
	private IMemberRecordService	memberRecordService;
	
	@Resource
	private IWinningRecordService	winningRecordService;
	
	@Resource
	private IMemberService			memberService;
	
	@Resource
	private IRuleSetService			ruleSetService;
	
	@Resource
	private IMemberLevelService		memberLevelService;
	
	@Resource
	private IDrawLevelGroupService	drawLevelGroupService;
	
	@Resource
	private IPrizeService			prizeService;
	
	@Resource
	private IDrawNumService			drawNumService;
	
	@Resource
	private IIntegralRecordService	integralRecordService;
	
	@Resource
	private IBalanceRecordService	balanceRecordService;
	
	@Resource
	private IRedPacketService		redPacketService;
	
	@Resource
	private IShoppingCartService	shoppingCartService;
	
	@Resource
	private LockDrawMapper			lockDrawMapper;
	
	@Resource
	private RedisUtils				redisUtils;
	
	/** 
	 *
	 * @Title: findById 
	 * @author: wuyicheng
	 * @date: 2017年5月5日下午12:00:23 
	 * @param id
	 * @return
	 * @throws 
	 */
	@Override
	public WinningRule findById(Long id) {
		return winningRuleMapper.findById(id);
	}
	
	/** 
	 *
	 * @Title: deleteByPrimaryKey 
	 * @author: wuyicheng
	 * @date: 2017年5月5日下午12:00:23 
	 * @param id
	 * @return
	 * @throws 
	 */
	@Override
	public int deleteByPrimaryKey(Long id) {
		WinningRule winningRule = new WinningRule();
		winningRule.setId(id);
		winningRule.setDelFlag(ConstantsUtil.DEL_FLAG_YES_1);
		return update(winningRule);
	}
	
	/** 
	 *
	 * @Title: insert 
	 * @author: wuyicheng
	 * @date: 2017年5月5日下午12:00:23 
	 * @param winningRule
	 * @return
	 * @throws 
	 */
	@Override
	public int insert(WinningRule winningRule) {
		winningRule.setCreateTime(DateUtils.getCurrentDateTime());
		winningRule.setUpdateTime(DateUtils.getCurrentDateTime());
		winningRule.setDelFlag(ConstantsUtil.DEL_FLAG_NO_0);
		return winningRuleMapper.insert(winningRule);
	}
	
	/** 
	 *
	 * @Title: update 
	 * @author: wuyicheng
	 * @date: 2017年5月5日下午12:00:23 
	 * @param winningRule
	 * @return
	 * @throws 
	 */
	@Override
	public int update(WinningRule winningRule) {
		winningRule.setUpdateTime(DateUtils.getCurrentDateTime());
		return winningRuleMapper.update(winningRule);
	}
	
	/** 
	 *
	 * @Title: countCanParticipateNumber 
	 * @author: wuyicheng
	 * @date: 2017年5月5日下午5:16:25 
	 * @param memberId
	 * @param sysId
	 * @return
	 * @throws 
	 */
	@Override
	public long countCanParticipateNumber(Long memberId, Long sysId) {
		// 默认每天都有1次抽奖机会
		long canParticipateNumber = 1;
		boolean isSignInToday = memberRecordService.isSignInToday(memberId, sysId);
		// 签到+1
		if (isSignInToday) {
			canParticipateNumber = canParticipateNumber + 1;
		}
		// 统计使用次数
		long useNumber = winningRecordService.countUseNumber(memberId, sysId);
		canParticipateNumber = canParticipateNumber - useNumber;
		if (canParticipateNumber < 0) {
			canParticipateNumber = 0;
		}
		return canParticipateNumber;
	}
	
	/** 
	 *
	 * @Title: getWinningResult 
	 * @author: wuyicheng
	 * @date: 2017年5月5日下午6:09:52 
	 * @param memberId
	 * @param sysId
	 * @return
	 * @throws 
	 */
	@Override
	public Result<Map<String, Object>> getWinningResult(Long memberId, Long sysId) {
		Result<Map<String, Object>> result = new Result<>();
		Map<String, Object> map = new HashMap<>();
		long nums = countCanParticipateNumber(memberId, sysId);
		if (nums > 0) {
			WinningRule winningRule = getWinningProSku(memberId, sysId);
			map.put(ConstantsUtil.PRO_SKU, winningRule.getProSku());
			map.put(ConstantsUtil.DESCRIPTION, winningRule.getDescription());
			result.setErrorCode(ErrorCode.SUCCESS);
			result.setData(map);
		} else {
			result.setErrorCode(ErrorCode.ELSE);
			// 今天抽奖次数已经用完
			result.setMessage("The number of lottery draws is running out today");
		}
		return result;
	}
	
	/** 
	 * 随机获取中奖规则
	 * 
	 * @Title: getWinningProSku 
	 * @author: wuyicheng
	 * @date: 2017年5月5日下午6:15:09 
	 * @param memberId
	 * @param sysId
	 * @return
	 * @return: WinningRule
	 * @throws 
	 */
	private WinningRule getWinningProSku(Long memberId, Long sysId) {
		WinningRule winningRule = getRandomRule();
		int totalNums = 0;
		int provideNums = 0;
		if (winningRule != null) {
			totalNums = winningRule.getNums() == null ? 0 : winningRule.getNums();
			provideNums = winningRule.getProvideNums() == null ? 0 : winningRule.getProvideNums();
			// 判断规则是否派发完毕
			// 奖品总数量大于派发数量=等于可派发数量
			if (WinningRule.FIVE_PRIZE_5 != winningRule.getId() && totalNums <= provideNums) {
				winningRule = winningRuleMapper.findById(WinningRule.FIVE_PRIZE_5);
			}
		} else {// 默认不中奖
			winningRule = winningRuleMapper.findById(WinningRule.FIVE_PRIZE_5);
		}
		// 派发+1
		winningRule.setProvideNums(winningRule.getProvideNums() + 1);
		winningRuleMapper.update(winningRule);
		// 记录中奖记录
		WinningRecord winningRecord = new WinningRecord();
		winningRecord.setMemberId(memberId);
		winningRecord.setSysId(sysId);
		winningRecord.setWinningRule(winningRule.getId());
		winningRecord.setProSku(winningRule.getProSku());
		winningRecord.setRemark(winningRule.getDescription());
		winningRecord.setIsGiving(WinningRecord.IS_GIVING_NO_0);
		Member member = memberService.findById(memberId);
		if (member != null) {
			winningRecord.setMobilePhone(member.getPhone());
		}
		winningRecordService.insert(winningRecord);
		return winningRule;
	}
	
	/** 
	 * 随机获取中奖规则
	 * 
	 * @Title: getRandomRule 
	 * @author: wuyicheng
	 * @date: 2017年5月5日下午6:51:02 
	 * @return
	 * @return: WinningRule
	 * @throws 
	 */
	@Override
	public WinningRule getRandomRule() {
		Random random = new Random();
		int randomNumber = random.nextInt(10000);
		WinningRule winningRule = null;
		List<WinningRule> winningRules = winningRuleMapper.searchCanUseRule();
		if (winningRules != null && winningRules.size() > 0) {
			int minNumber = 0;
			int maxNumber = 0;
			for (WinningRule rule : winningRules) {
				BigDecimal ratio = ArithUtil.mul(rule.getWinningRatio(), new BigDecimal(100));
				maxNumber = maxNumber + ratio.intValue();
				// 如果随机数落在这个区间，返回规则
				if (randomNumber > minNumber && randomNumber <= maxNumber) {
					return rule;
				}
				minNumber = maxNumber;
			}
		}
		return winningRule;
	}
	
	/**
	 * 根据奖品类型 对奖品进行派发
	 * @throws CustomException 
	 * @throws ParseException 
	 */
	public boolean distributePrize(Prize prize, Long memberId, Long sysId, RuleSet ruleSet) throws CustomException, ParseException {
		boolean isSuccess = true;
		WinningRecord winningRecord = new WinningRecord();
		Member member = memberService.findById(memberId);
		
		if (member != null) {
			winningRecord.setMobilePhone(member.getPhone());
		}
		if (prize != null) {
			// 记录中奖记录
			
			/*	prize.setUsePrizeQuantity(ArithUtil.add(new BigDecimal(prize.getUsePrizeQuantity()), new BigDecimal()).intValue());
			prizeService.updatePrize(prize);*/
			prizeService.updateUseNumPrize(prize, 1);
			
			winningRecord.setMemberId(memberId);
			winningRecord.setSysId(sysId);
			winningRecord.setWinningRule(ruleSet.getId());
			winningRecord.setProSku(prize.getPrizeNo());
			winningRecord.setRemark(prize.getAbbreviation());
			winningRecord.setPrizeId(prize.getId());
			winningRecord.setPrizeType(prize.getPrizeType());
			winningRecord.setUnit(prize.getUnit());
			winningRecord.setDelFlag(ConstantsUtil.DEL_FLAG_YES_1);
			winningRecord.setPrompt(prize.getPrompt());
			winningRecord.setAbbreviation(prize.getAbbreviation());
			winningRecord.setProbability(prize.getProbability());
			winningRecord.setIsGiving(WinningRecord.IS_GIVING_YES_1);// 除了其他的类型 都设为已派发
			if (PrizeType.GIVE_OTHER.toString().equals(prize.getPrizeType())) {
				winningRecord.setIsGiving(WinningRecord.IS_GIVING_NO_0);
			}
			winningRecordService.insert(winningRecord);
			
			// 送积分
			if (PrizeType.GIVE_INTEGRAL.toString().equals(prize.getPrizeType())) {
				integralRecordService.addIntegralRecord(memberId, sysId, null, null, prize.getOneNum().intValue(), IntegralType.DRAW_GIVE, "抽奖", ruleSet.getShowName(), "",
						IntegralRecord.IS_BUY_NO);
			}
			// 送抽奖次数
			if (PrizeType.GIVE_DRAW_NUM.toString().equals(prize.getPrizeType())) {
				
				if (!StringUtil.isBlank(prize.getPrizeNo()) && prize.getOneNum() != null && prize.getOneNum().intValue() > 0) {
					String[] no = prize.getPrizeNo().split(",");
					for (int i = 0; i < no.length; i++) {
						drawNumService.modityDrawNum(memberId, Long.valueOf(no[i]), sysId, prize.getOneNum().intValue(), null);
					}
				}
			}
			// 送充值
			if (PrizeType.GIVE_TOPUP_BALANCE.toString().equals(prize.getPrizeType())) {
				balanceRecordService.updateBalance(memberId, sysId, null, null, prize.getOneNum(), BalanceType.DRAW_GIVE, "抽奖", ruleSet.getShowName(), "", BalanceRecord.IS_BUY_NO);
				
			}
			// 送红包
			if (PrizeType.GIVE_RED_PACKET.toString().equals(prize.getPrizeType())) {
				if (!StringUtil.isBlank(prize.getPrizeNo()) && prize.getOneNum() != null && prize.getOneNum().intValue() > 0) {
					String[] no = prize.getPrizeNo().split(",");
					List<Long> ruleIds = new ArrayList<>();
					for (int i = 0; i < no.length; i++) {
						ruleIds.add(Long.valueOf(no[i]));
					}
					isSuccess = redPacketService.sendRedPacket(ruleIds, sysId, prize.getOneNum().intValue(), memberId, SysUser.SYS_USER, winningRecord.getId(),
							RuleType.DRAW.toString() + "_" + PrizeType.GIVE_RED_PACKET.toString(), null);
					if (!isSuccess) {
						winningRecord.setIsGiving(WinningRecord.IS_GIVING_NO_0);
						winningRecordService.update(winningRecord);
					}
				}
			}
			// 送商品
			if (PrizeType.GIVE_PRO.toString().equals(prize.getPrizeType())) {
				if (!StringUtil.isBlank(prize.getPrizeNo()) && prize.getOneNum() != null && prize.getOneNum().intValue() > 0) {
					String[] no = prize.getPrizeNo().split(",");
					List<String> skus = new ArrayList<>();
					for (int i = 0; i < no.length; i++) {
						skus.add(no[i]);
					}
					shoppingCartService.addPremium(skus, sysId, memberId, prize.getOneNum(), ruleSet.getId(), ruleSet.getShowName());
				}
			}
			
		} else {
			// 奖品为空
			winningRecord.setMemberId(memberId);
			winningRecord.setSysId(sysId);
			winningRecord.setWinningRule(ruleSet.getId());
			winningRecord.setRemark("谢谢参与");
			winningRecord.setDelFlag(ConstantsUtil.DEL_FLAG_YES_1);
			winningRecord.setAbbreviation("谢谢参与");
			winningRecordService.insert(winningRecord);
		}
		return isSuccess;
	}
	
	/**
	 * 抽奖
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public synchronized Result<Prize> getDrawResult(Long memberId, Long sysId, String serialNumber, String device) throws ParseException, CustomException {
		Result<Prize> res = new Result<>();
		RuleSet ruleSet = ruleSetService.selectBySerialNumber(serialNumber);
		if (ruleSet == null || !(ruleSet.getSysId().equals(sysId)) || !(RuleType.DRAW.toString().equals(ruleSet.getRuleType()))) {
			throw new CustomException(ErrorCode.RULE_NULL.getCode(), "查无规则");
		}
		
		Long ruleId = ruleSet.getId();
		
		if (!(Status.ALR_ENABLE.toString().equals(ruleSet.getStatus()))) {
			throw new CustomException(ErrorCode.RULE_STATUS_NO_ENABLE.getCode(), "规则未激活");
		}
		Long currTime = new Date().getTime();
		Long startTime = DateUtils.parseFullTime(ruleSet.getStartTime()).getTime();
		Long endTime = DateUtils.parseFullTime(ruleSet.getEndTime()).getTime();
		/*		if (!(startTime <= currTime && currTime <= endTime)) {
					// log.info("不再活动时间里开始时间{},结束时间{}当前时间{}", ruleSet.getStartTime(), ruleSet.getEndTime());
					System.out.println("endTime:" + endTime);
					System.out.println("startTime:" + startTime);
					System.out.println("currTime:" + currTime);
					throw new CustomException(ErrorCode.RULE_OUT_TIME.getCode(), "不再活动时间里");
				}
				*/
		if (!(startTime <= currTime)) {
			throw new CustomException(ErrorCode.RULE_OUT_TIME.getCode(), "活动开始于" + ruleSet.getStartTime() + ",请敬请期待!");
		}
		
		if (!(currTime <= endTime)) {
			throw new CustomException(ErrorCode.RULE_OUT_TIME.getCode(), "活动已经结束,谢谢您的参与!");
		}
		
		if (!ruleSet.getDevice().contains(device)) {
			throw new CustomException(ErrorCode.RULE_DEVICE.getCode(), "该规则不能在" + device + "上使用");
		}
		MemberLevel memberLevel = memberLevelService.findByMemberIdAndSysId(memberId, sysId);
		
		if (memberLevel == null) {
			throw new CustomException(ErrorCode.RULE_OUT_MEMBER_LEVEL.getCode(), "会员等级不符合要求");
		}
		DrawLevelGroup temp = new DrawLevelGroup();
		temp.setRuleId(ruleId);
		
		List<DrawLevelGroup> drawLevelGroupList = drawLevelGroupService.findAllDrawLevelGroup(temp);
		DrawLevelGroup canUseDrawLevelGroup = findCanUseDrawLevelGroup(drawLevelGroupList, memberLevel);
		
		if (canUseDrawLevelGroup == null) {
			throw new CustomException(ErrorCode.RULE_OUT_MEMBER_LEVEL.getCode(), "会员等级不符合要求");
		}
		RedisTemplate redisTemplate = redisUtils.getRedisTemplate();
		if (redisTemplate != null) {
			// 判断能否抽奖 、、并发
			isCanDraw(redisTemplate, memberId, sysId, ruleId, memberLevel, canUseDrawLevelGroup);
		} else {
			throw new CustomException(ErrorCode.NOT_FIND.getCode(), "redis模版获取失败");
		}
		
		List<Long> groupIds = new ArrayList<>();
		groupIds.add(canUseDrawLevelGroup.getId());
		List<Prize> canUsePrizeList = prizeService.findAllPrizeByGroupIds(groupIds);
		Prize canUsePrize = getRandomPrize(canUsePrizeList); // 中奖的奖品
		Prize defaultPrize = getDefaultPrize(canUsePrizeList); // 默认奖品
		
		// 100%中奖
		if (DrawLevelGroup.WINNING_TYPE_1.equals(canUseDrawLevelGroup.getWinningType())) {
			if (defaultPrize == null) {
				throw new CustomException(ErrorCode.PRIZE_NULL.getCode(), "100%中奖的默认奖品不能为空");
			}
			if (canUsePrize == null) {
				distributePrize(defaultPrize, memberId, sysId, ruleSet);// 对奖品进行派发
				res.setErrorCode(ErrorCode.SUCCESS);
				res.setData(defaultPrize);
				return res;
			} else {
				// 中奖是默认奖品 直接返回，不是的话判断数量
				if (Prize.DEFAULT_YES.equals(canUsePrize.getIsDefault())) {
					distributePrize(canUsePrize, memberId, sysId, ruleSet);// 对奖品进行派发
					res.setErrorCode(ErrorCode.SUCCESS);
					res.setData(canUsePrize);
					return res;
				}
				// 判断数量 不够的话 返回默认
				BigDecimal canUsePrizeNum = ArithUtil.sub(new BigDecimal(canUsePrize.getPrizeQuantity()), new BigDecimal(canUsePrize.getUsePrizeQuantity()));
				if (canUsePrize.getPrizeQuantity().intValue() > 0 && canUsePrizeNum.intValue() >= 0 && canUsePrize.getUsePrizeQuantity() < canUsePrize.getPrizeQuantity()) {
					boolean isLock = isLockDraw(canUsePrize);
					if (isLock) {
						distributePrize(defaultPrize, memberId, sysId, ruleSet);// 对奖品进行派发
						res.setErrorCode(ErrorCode.SUCCESS);
						res.setData(null);
						return res;
					}
					res.setErrorCode(ErrorCode.SUCCESS);
					res.setData(canUsePrize);
					distributePrize(canUsePrize, memberId, sysId, ruleSet);// 对奖品进行派发
					return res;
				} else {
					distributePrize(defaultPrize, memberId, sysId, ruleSet);// 对奖品进行派发
					res.setErrorCode(ErrorCode.SUCCESS);
					res.setData(defaultPrize);
					return res;
				}
			}
		} else {
			// 非100%中奖
			if (canUsePrize == null) {
				res.setErrorCode(ErrorCode.SUCCESS);
				res.setData(null);
				distributePrize(null, memberId, sysId, ruleSet);// 对奖品进行派发
				return res;
			}
			BigDecimal canUsePrizeNum = ArithUtil.sub(new BigDecimal(canUsePrize.getPrizeQuantity()), new BigDecimal(canUsePrize.getUsePrizeQuantity()));
			
			if (canUsePrize.getPrizeQuantity().intValue() > 0 && canUsePrizeNum.intValue() >= 0 && canUsePrize.getUsePrizeQuantity() < canUsePrize.getPrizeQuantity()) {
				boolean isLock = isLockDraw(canUsePrize);
				if (isLock) {
					distributePrize(null, memberId, sysId, ruleSet);// 对奖品进行派发
					res.setErrorCode(ErrorCode.SUCCESS);
					res.setData(null);
					return res;
				}
				res.setErrorCode(ErrorCode.SUCCESS);
				distributePrize(canUsePrize, memberId, sysId, ruleSet);// 对奖品进行派发
				res.setData(canUsePrize);
				return res;
			} else {
				distributePrize(null, memberId, sysId, ruleSet);// 对奖品进行派发
				res.setErrorCode(ErrorCode.SUCCESS);
				res.setData(null);
				return res;
			}
		}
	}
	
	/**
	 * 并发  判断能不能抽奖
	 * @Title: isCanDraw 
	 * @Description: TODO
	 * @author xujinding
	 * @param @param redisTemplate
	 * @param @param memberId
	 * @param @param sysId
	 * @param @param ruleId
	 * @param @param memberLevel
	 * @param @param canUseDrawLevelGroup
	 * @param @throws CustomException
	 * @return void
	 * @throws
	 */
	public void isCanDraw(RedisTemplate redisTemplate, Long memberId, Long sysId, Long ruleId, MemberLevel memberLevel, DrawLevelGroup canUseDrawLevelGroup)
			throws CustomException {
		
		RedisLock lock = new RedisLock(redisTemplate, "getDrawResult" + memberId, 10000, 20000);
		try {
			if (lock.lock()) {
				// 需要加锁的代码
				// 判断抽奖次数
				boolean isDrawNum = drawNumService.isCanDraw(memberId, ruleId, sysId);
				
				if (!isDrawNum) {
					throw new CustomException(ErrorCode.DRAW_NUM_OUT.getCode(), "抽奖次数不足");
				}
				
				// 将抽奖次数-1
				if ((drawNumService.modityDrawNumLock(memberId, ruleId, sysId, -1, null)) < 1) {
					throw new CustomException(ErrorCode.DRAW_NUM_OUT.getCode(), "抽奖次数不足");
				}
			}
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			// 为了让分布式锁的算法更稳键些，持有锁的客户端在解锁之前应该再检查一次自己的锁是否已经超时，再去做DEL操作，因为可能客户端因为某个耗时的操作而挂起，
			// 操作完的时候锁因为超时已经被别人获得，这时就不必解锁了。 ————这里没有做
			// lock.unlock();
			redisUtils.del(lock.getLockKey());
		}
		
	}
	
	/**
	 * 防止并发锁
	 * @Title: isLockDraw 
	 * @Description: TODO
	 * @author xujinding
	 * @param @param canUsePrize
	 * @return void
	 * @throws
	 */
	public boolean isLockDraw(Prize canUsePrize) {
		
		Prize lockPrize = new Prize();
		lockPrize.setUsePrizeQuantity(canUsePrize.getUsePrizeQuantity());
		lockPrize.setPrizeQuantity(canUsePrize.getPrizeQuantity());
		try {
			LockDraw record = new LockDraw();
			record.setNum(canUsePrize.getUsePrizeQuantity());
			record.setPrizeId(canUsePrize.getId());
			lockDrawMapper.insertSelective(record);
			return false;
		} catch (Exception e) {
			lockPrize.setUsePrizeQuantity(canUsePrize.getUsePrizeQuantity() + 1);
			if (lockPrize.getPrizeQuantity().intValue() < lockPrize.getUsePrizeQuantity()) {
				return true;
			}
			return isLockDraw(lockPrize);
		}
	}
	
	/**
	 * 取出奖品列表的默认奖品
	 * @param prizes
	 * @return
	 */
	public Prize getDefaultPrize(List<Prize> prizes) {
		if (prizes != null && prizes.size() > 0) {
			for (Prize p : prizes) {
				if (Prize.DEFAULT_YES.equals(p.getIsDefault())) {
					return p;
				}
			}
		}
		return null;
		
	}
	
	/**
	 * 根据会员等级查询可用的等级
	 * @param drawLevelGroupList
	 * @return
	 */
	public DrawLevelGroup findCanUseDrawLevelGroup(List<DrawLevelGroup> drawLevelGroupList, MemberLevel memberLevel) {
		// 查找一个可用的分组
		if (drawLevelGroupList != null && drawLevelGroupList.size() > 0) {
			for (DrawLevelGroup dg : drawLevelGroupList) {
				if (!StringUtil.isBlank(dg.getLevel())) {
					String[] memberLevels = dg.getLevel().split(",");
					if (memberLevels != null && memberLevels.length > 0) {
						for (String ml : memberLevels) {
							if (ml.equals(memberLevel.getId() + "")) {
								return dg;
							}
						}
					}
				}
			}
		}
		
		return null;
	}
	
	/** 
	 * 根据概率获取中奖奖品（没处理奖品数量）
	 * 
	 * @Title: getRandomRule 
	 * @author: xujinding
	 * @date: 2017年5月5日下午6:51:02 
	 * @return
	 * @return: WinningRule
	 * @throws 
	 */
	public Prize getRandomPrize(List<Prize> prizeList) {
		
		// 10% 1~1000
		// 5% 1~1500
		// 17.53% 1501~3253
		// 0%
		// 50% 3254-8254
		Random random = new Random();
		int randomNumber = random.nextInt(10000) + 1;// 产生 1~10000的随机数
		if (prizeList != null && prizeList.size() > 0) {
			int minNumber = 1;
			int maxNumber = 0;
			for (Prize pri : prizeList) {
				BigDecimal ratio = ArithUtil.mul(pri.getProbability(), new BigDecimal(100));
				if (ratio.doubleValue() > 0) {
					maxNumber = maxNumber + ratio.intValue();
					// 如果随机数落在这个区间
					if (randomNumber >= minNumber && randomNumber <= maxNumber) {
						return pri;
					}
					minNumber = maxNumber + 1;
				}
			}
		}
		return null;
	}
	
	public static void main(String[] args) throws ParseException, CustomException {
		for (int i = 0; i < 100; i++) {
			if (!(DateUtils.parseFullTime("2017-03-06 00:00:00").getTime() <= (new Date().getTime())
					&& (new Date().getTime()) <= DateUtils.parseFullTime("2017-07-30 00:00:00").getTime())) {
				// log.info("不再活动时间里开始时间{},结束时间{}当前时间{}", ruleSet.getStartTime(), ruleSet.getEndTime());
				System.out.println("fda");
			}
			
		}
		
	}
}
